package com.community.common.service;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.community.common.config.BizException;
import com.community.common.mapper.DicMapper;
import com.community.common.pojo.domain.Dic;
import com.community.common.pojo.dto.DicDto;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 * 服务类
 * </p>
 *
 * @author jobob
 * @since 2021-01-21
 */
@Slf4j
@Service
@Transactional(rollbackFor = Exception.class)
public class DicService {

    @Resource
    DicMapper dicMapper;

    public void batchInsert(DicDto dicDto) {
        if (ObjectUtils.isEmpty(dicDto) || StringUtils.isAnyBlank(dicDto.getData(), dicDto.getType())) {
            throw new BizException("数据为空");
        }
        List<Dic> dicList = JSON.parseArray(dicDto.getData(), Dic.class);
        if (CollectionUtils.isEmpty(dicList)) {
            throw new BizException("数据集合为空");
        }
        QueryWrapper<Dic> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("lx", dicDto.getType());
        List<Dic> queryList = dicMapper.selectList(queryWrapper);
        if (!ObjectUtils.isEmpty(queryList) && queryList.size() > 0) {
            throw new BizException("该类型字典数据已有");
        }
        for (Dic dic : dicList) {
            dic.setLx(dicDto.getType());
            dicMapper.insert(dic);
        }
    }


    public List<Dic> list(String type) {
        if (StringUtils.isAnyBlank(type)) {
            throw new BizException("参数为空");
        }
        QueryWrapper<Dic> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("lx", type);
        return dicMapper.selectList(queryWrapper);
    }

}
